<template>
  <div class="flex items-center" :class="divClass">
    <ElInputNumber
      v-bind="getBindValue"
      v-model="num1"
      :placeholder="startPlaceholder || getBindValue.placeholder"
      :min="startMin"
      :max="getStartMax"
      @change="startChange"
    />
    <slot name="center">
      <div class="mx-[3px]">{{ rangeSeparator }}</div>
    </slot>
    <ElInputNumber
      v-bind="getBindValue"
      v-model="num2"
      :placeholder="endPlaceholder || getBindValue.placeholder"
      :min="getEndMin"
      :max="endMax"
      @change="endChange"
    />
  </div>
</template>

<script lang="ts" setup>
// eslint-disable-next-line no-undef
defineOptions({ name: 'InputNumberGroup' })

import type { Recordable } from '@/types/global'
import { propTypes } from '@/types/propTypes'
import { isArray, isUndefined } from 'lodash-es'
import { computed, ref, useAttrs, watch } from 'vue'
import { ElInputNumber } from 'element-plus'

const attrs = useAttrs()
const emit = defineEmits(['startChange', 'endChange', 'update:model-value'])
const props = defineProps({
  modelValue: {
    type: [String, Array],
  },
  startPlaceholder: {
    type: String,
  },
  endPlaceholder: {
    type: String,
  },
  rangeSeparator: propTypes.string.def('至'),
  startMin: propTypes.number.def(0),
  startMax: propTypes.number,
  endMin: propTypes.number.def(0),
  endMax: propTypes.number,
  divClass: propTypes.string.def('mt-[2px]'),
  /**开始结束是否关联 */
  startRelatedEnd: propTypes.bool.def(true),
})

let num1 = ref<number>()
let num2 = ref<number>()
const getStartMax = computed(() => {
  let num = props.startMax
  if (props.startRelatedEnd && num2.value) {
    num = num2.value
  }
  return num
})
const getEndMin = computed(() => {
  let num = props.endMin
  if (props.startRelatedEnd && num1.value) {
    num = num1.value
  }
  return num
})

const getBindValue = computed(() => {
  const att = {
    ...attrs,
    ...props,
  }
  // console.log('att', att);
  return att as Recordable
})
watch(
  () => props.modelValue,
  (val: any) => {
    // console.log('1111111111111', val);
    if (isUndefined(val)) {
      num1.value = undefined
      num2.value = undefined
    } else if (!isArray(val)) {
      console.error('InputNumberGroup传入值不是数组或者undefined')
    } else {
      num1.value = val[0]
      num2.value = val[1]
    }
  },
  {
    deep: true,
    immediate: true,
  },
)
function startChange(e: any) {
  // console.log('eeee', e);
  emit('startChange', e)
  if (!isUndefined(num1.value) && !isUndefined(num2.value)) {
    emit('update:model-value', [num1.value, num2.value])
  }
}
function endChange(e: any) {
  emit('endChange', e)
  // console.log('num1', num1.value, num2.value);
  if (!isUndefined(num1.value) && !isUndefined(num2.value)) {
    emit('update:model-value', [num1.value, num2.value])
  }
}
</script>

<style lang="scss" scoped></style>
